<?php
class Management extends CI_Controller {
	
	function Management (){
		parent::__construct();
		$this->load->model(array('disability_model', 'leadership_model', 'buddyType_model', 'user_model', 'club_model', 'institution_model', 'employee_model', 'activity_model'));
		if($this->session->userdata('COD_POS_LIDERAZGO') != 100000){
			$this->load->helper('url');
			redirect('/home/denied');
		}
	}
	
	public function index(){
		$this->load->view('management/index');
	}
	
	public function new_institution(){
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('code', 'Code', 'required');
		$this->form_validation->set_rules('rif', 'Rif', 'required');
		$this->form_validation->set_rules('address', 'Address', 'required');
		$this->form_validation->set_rules('country', 'Country', 'required');
		$this->form_validation->set_rules('state', 'State', 'required');
		$this->form_validation->set_rules('municipality', 'Municipality', 'required');
		$this->form_validation->set_rules('avenue', 'Avenue', 'required');
		$this->form_validation->set_rules('street', 'Street', 'required');
		$this->form_validation->set_rules('parish', 'Parish', 'required');
		$this->form_validation->set_rules('phone', 'Phone', 'required|numeric');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('contactName', 'ContactName', 'required');
		$this->form_validation->set_rules('contactPhone', 'ContactPhone', 'required|numeric');
		$this->form_validation->set_rules('contactEmail', 'ContactEmail', 'required|valid_email');
		$this->form_validation->set_rules('institutionType', 'InstitutionType', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['institutionTypes'] = $this->institution_model->get_active_types();
			
			$this->load->view('management/registry/new_institution', $data);
		}
		else
		{
			$data ['codigo'] = $_POST["code"];
			$data ['nombre'] = $_POST["name"];
			$data ['rif'] = $_POST["rif"];
			$data ['direccion'] = $_POST["address"];
			$data ['calle'] = $_POST["street"];
			$data ['avenida'] = $_POST["avenue"];
			$data ['parroquia'] = $_POST["parish"];
			$data ['municipio'] = $_POST["municipality"];
			$data ['estado'] = $_POST["state"];
			$data ['pais'] = $_POST["country"];
			$data ['pto_referencia'] = $_POST["referencePoint"];
			$data ['telefono'] = $_POST["phone"];
			$data ['telefono_fax'] = $_POST["fax"];
			$data ['email'] = $_POST["email"];
			$data ['twitter'] = $_POST["twitter"];
			$data ['facebook'] = $_POST["facebook"];
			$data ['pag_web'] = $_POST["webpage"];
			$data ['TIPO_COD_INST_EDU'] = $_POST["institutionType"];
			$data ['nombre_persona_contacto'] = $_POST["contactName"];
			$data ['telefono_persona_contacto'] = $_POST["contactPhone"];
			$data ['correo_persona_contacto'] = $_POST["contactEmail"];
	
			$this->institution_model->insert_institution($data);	
			$this->index();		
		}
	}
	
	public function new_club(){
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('code', 'Code', 'required');
		$this->form_validation->set_rules('address', 'Address', 'required');
		$this->form_validation->set_rules('country', 'Country', 'required');
		$this->form_validation->set_rules('state', 'State', 'required');
		$this->form_validation->set_rules('municipality', 'Municipality', 'required');
		$this->form_validation->set_rules('avenue', 'Avenue', 'required');
		$this->form_validation->set_rules('street', 'Street', 'required');
		$this->form_validation->set_rules('parish', 'Parish', 'required');
		$this->form_validation->set_rules('phone', 'Phone', 'required|numeric');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('contactName', 'ContactName', 'required');
		$this->form_validation->set_rules('contactPhone', 'ContactPhone', 'required|numeric');
		$this->form_validation->set_rules('contactEmail', 'ContactEmail', 'required|valid_email');
		$this->form_validation->set_rules('id_institution', 'Id_institution', 'required');
		$this->form_validation->set_rules('id_employee', 'Id_employee', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['institutions'] = $this->institution_model->get_all();
			$data['employees'] = $this->employee_model->get_all();
			
			$this->load->view('management/registry/new_club', $data);
		}
		else
		{
			$data ['codigo'] = $_POST["code"];
			$data ['nombre'] = $_POST["name"];
			$data ['direccion'] = $_POST["address"];
			$data ['calle'] = $_POST["street"];
			$data ['avenida'] = $_POST["avenue"];
			$data ['parroquia'] = $_POST["parish"];
			$data ['municipio'] = $_POST["municipality"];
			$data ['estado'] = $_POST["state"];
			$data ['pais'] = $_POST["country"];
			$data ['pto_referencia'] = $_POST["referencePoint"];
			$data ['telefono'] = $_POST["phone"];
			$data ['email'] = $_POST["email"];
			$data ['twitter'] = $_POST["twitter"];
			$data ['facebook'] = $_POST["facebook"];
			$data ['pag_web'] = $_POST["webpage"];
			$data ['ID_INSTITUCION'] = $_POST["id_institution"];
			$data ['ID_EMPLEADO_FUNDACION'] = $_POST["id_employee"];
			$data ['nombre_persona_contacto'] = $_POST["contactName"];
			$data ['telefono_persona_contacto'] = $_POST["contactPhone"];
			$data ['correo_persona_contacto'] = $_POST["contactEmail"];
	
			$this->club_model->insert_club($data);	
			$this->index();		
		}
	}
	
	//----------------------------EMPLOYEES-----------------------------------------------
	public function employees($msg){
		$data['employees'] = $this->employee_model->get_all();
		$data['msg'] = $msg;
		$this->load->view('management/foundation/employee/employees', $data);
	}
	
	public function employee_detail($id){
		$data['employee'] = $this->employee_model->get_employee($id, "id_empleado");
		$this->load->view('management/foundation/employee/employee_detail', $data);
	}
	
	public function update_employee_status(){
		$employee = $this->employee_model->get_employee($_POST["id_user"], 'id_empleado');
		$data = array('condicion' => 'inactivo');
		if($employee[0]['condicion'] == 'inactivo')
			$data = array('condicion' => 'activo');
		
		$this->employee_model->update_employee($employee[0]['id_empleado'], $data);
		$this->employees('Informacion de empleado actualizada exitosamente');
	}
	
	public function new_employee(){
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('lastname', 'Lastname', 'required');
		$this->form_validation->set_rules('ci', 'Ci', 'required');
		$this->form_validation->set_rules('genre', 'Genre', 'required');
		$this->form_validation->set_rules('birthdate', 'Birthdate', 'required');
		$this->form_validation->set_rules('phone', 'phone', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('position', 'Position', 'callback_position_check');
		$this->form_validation->set_rules('boss', 'Boss', 'callback_boss_check');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['positions'] = $this->employee_model->get_charges();
			$data['employees'] = $this->employee_model->get_all();	
					
			$this->load->view('management/foundation/employee/new_employee', $data);
		}
		else
		{
			$data ['ci_empleado'] = $_POST["ci"];
			$data ['nombre'] = $_POST["name"];
			$data ['apellido'] = $_POST["lastname"];
			$data ['genero'] = $_POST["genre"];
			$data ['fecha_nacimiento'] = change2ymd($_POST["birthdate"]);
			$data ['telefono'] = $_POST["phone"];
			$data ['correo_electronico'] = $_POST["email"];
			$data ['twitter'] = $_POST["twitter"];
			$data ['facebook'] = $_POST["facebook"];
			$data ['ID_JEFE_INMEDIATO'] = $_POST["boss"];
			$data ['COD_CARGO'] = $_POST["position"];
			$data['condicion'] = 'activo';
			$data['ID_FUNDACION'] = 1; //ID fijo de la fundacion.
	
			$this->employee_model->insert_employee($data);	
			$this->employees('Empleado agregado exitosamente');		
		}
	}
	
	function boss_check($str)
	{
		if ($str == '-')
		{
			$this->form_validation->set_message('boss_check', 'Debe seleccionar un valor v&aacute;lido');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function position_check($str)
	{
		if ($str == '-')
		{
			$this->form_validation->set_message('position_check', 'Debe seleccionar un valor v&aacute;lido');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_employee($id){
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('lastname', 'Lastname', 'required');
		$this->form_validation->set_rules('ci', 'Ci', 'required');
		$this->form_validation->set_rules('genre', 'Genre', 'required');
		$this->form_validation->set_rules('birthdate', 'Birthdate', 'required');
		$this->form_validation->set_rules('phone', 'phone', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('position', 'Position', 'callback_position_check');
		$this->form_validation->set_rules('boss', 'Boss', 'callback_boss_check');
		$this->form_validation->set_rules('status', 'Status', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['positions'] = $this->employee_model->get_charges();
			$data['employees'] = $this->employee_model->get_all();	
			$data['employee'] = $this->employee_model->get_employee($id, 'id_empleado');
			$data['employee'] = $data['employee'][0];
					
			$this->load->view('management/foundation/employee/edit_employee', $data);
		}
		else
		{
			$data ['ci_empleado'] = $_POST["ci"];
			$data ['nombre'] = $_POST["name"];
			$data ['apellido'] = $_POST["lastname"];
			$data ['genero'] = $_POST["genre"];
			$data ['fecha_nacimiento'] = change2ymd($_POST["birthdate"]);
			$data ['telefono'] = $_POST["phone"];
			$data ['correo_electronico'] = $_POST["email"];
			$data ['twitter'] = $_POST["twitter"];
			$data ['facebook'] = $_POST["facebook"];
			$data ['ID_JEFE_INMEDIATO'] = $_POST["boss"];
			$data ['COD_CARGO'] = $_POST["position"];
			$data['condicion'] = $_POST["status"];
			$data['ID_FUNDACION'] = 1; //ID fijo de la fundacion.
	
			$this->employee_model->update_employee($id, $data);	
			$this->employees('Informacion de empleado actualizada exitosamente');	
		}
	}
	//--------------------------------END OF EMPLOYEES------------------------------------------------------
	
	//------------------------------FOUNDATION------------------------------------------------------
	function foundation($editable){
		$data['foundation'] = $this->employee_model->get_foundation();
		$data['foundation'] = $data['foundation'][0];
		if($editable == 'editable')
			$data['editable'] = "";
		else
			$data['editable'] = $editable;
		$this->load->view('management/foundation/information/index', $data);
	}
	
	function update_foundation(){
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('rif', 'Rif', 'required');
		$this->form_validation->set_rules('address', 'Adress', 'required');
		$this->form_validation->set_rules('country', 'Country', 'required');
		$this->form_validation->set_rules('state', 'State', 'required');
		$this->form_validation->set_rules('municipality', 'Municipality', 'required');
		$this->form_validation->set_rules('parish', 'Parish', 'required');
		$this->form_validation->set_rules('avenue', 'Avenue', 'required');
		$this->form_validation->set_rules('street', 'Street', 'required');
		$this->form_validation->set_rules('reference_point', 'Reference_point', 'required');
		$this->form_validation->set_rules('business_address', 'Business_address', 'required');
		$this->form_validation->set_rules('phone', 'Phone', 'required|numeric');
		$this->form_validation->set_rules('fax', 'Fax', 'required|numeric');
		$this->form_validation->set_rules('business_email', 'Business_email', 'required|valid_email');
		$this->form_validation->set_rules('email_name', 'Email_name', 'required');
		$this->form_validation->set_rules('info_email', 'Info_email', 'required|valid_email');
		$this->form_validation->set_rules('web_page', 'Web_page', 'required');
		$this->form_validation->set_rules('twitter', 'Twitter', 'required');
		$this->form_validation->set_rules('facebook', 'Facebook', 'required');
		$this->form_validation->set_rules('rep_name', 'Rep_name', 'required');
		$this->form_validation->set_rules('rep_ci', 'Rep_ci', 'required');
		$this->form_validation->set_rules('rep_email', 'Rep_email', 'required|valid_email');
		$this->form_validation->set_rules('rep_phone', 'Rep_phone', 'required|numeric');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->foundation("editable");
		}
		else
		{
			$data ['rif_fundacion'] = $_POST["rif"];
			$data ['nombre_fundacion'] = $_POST["name"];
			$data ['direccion_fiscal_fundacion'] = $_POST["address"];
			$data ['avenida'] = $_POST["avenue"];
			$data ['calle'] = $_POST["street"];
			$data ['parroquia'] = $_POST["parish"];
			$data ['municipio'] = $_POST["municipality"];
			$data ['estado'] = $_POST["state"];
			$data ['pais'] = $_POST["country"];
			$data ['pto_referencia'] = $_POST["reference_point"];
			$data ['direccion_comercial'] = $_POST["business_address"];
			$data['telefono'] = $_POST["phone"];
			$data['telefono_fax'] = $_POST["fax"];
			$data['nombre_envio_correo'] = $_POST["email_name"];
			$data['correo_recibo_de_información'] = $_POST["info_email"];
			$data['pag_web'] = $_POST["web_page"];
			$data['twitter'] = $_POST["twitter"];
			$data['facebook'] = $_POST["facebook"];
			$data['representante_legal'] = $_POST["rep_name"];
			$data['ci_representante_legal'] = $_POST["rep_ci"];
			$data['correo_representante'] = $_POST["rep_email"];
			$data['telefono_representante'] = $_POST["rep_phone"];
			$data['id_fundacion'] = 1; //ID fijo de la fundacion.
	
			$this->employee_model->update_foundation($data);	
			$this->foundation("readonly");		
		}
	}
	//------------------------------------END OF FOUNDATION--------------------------------------------
	
	//------------------------------------TYPE OF BUDDY------------------------------------------------
	function type_of_buddy($msg){
		$data['types'] = $this->buddyType_model->all();
		$data['msg'] = $msg;
		$this->load->view('management/tables/type_of_buddy/index', $data);
	}
	
	function new_type_of_buddy(){
		$this->form_validation->set_rules('buddyTypeCode', 'BuddyTypeCode', 'required|numeric|callback_buddyTypeCode_check');
		$this->form_validation->set_rules('description', 'Description', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('management/tables/type_of_buddy/new_type');
		}
		else
		{
			$data ['cod_tipo_buddy'] = $_POST["buddyTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = 'activo';
	
			$this->buddyType_model->insert($data);	
			$this->type_of_buddy('Nuevo tipo de buddy guardado exitosamente');		
		}
	}
	
	function buddyTypeCode_check($str)
	{
		$types = $this->buddyType_model->all();
		$exist = false;
		foreach($types as $t){
			if($t['cod_tipo_buddy'] == $str)
				$exist = true;
		}
		
		if ($exist)
		{
			$this->form_validation->set_message('buddyTypeCode_check', 'El c&oacute;digo ya existe, introduzca uno nuevo.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_type_of_buddy($code){
		$this->form_validation->set_rules('buddyTypeCode', 'BuddyTypeCode', 'required');
		$this->form_validation->set_rules('description', 'Description', 'required');
		$this->form_validation->set_rules('condition', 'Condition', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['type'] = $this->buddyType_model->find($code);
			$data['type'] = $data['type'][0];
			$this->load->view('management/tables/type_of_buddy/edit_type', $data);
		}
		else
		{
			$data ['cod_tipo_buddy'] = $_POST["buddyTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = $_POST["condition"];
	
			$this->buddyType_model->update($data);	
			$this->type_of_buddy('El tipo de buddy ha sido actualizado exitosamente');		
		}
	}
	
	function inactivate_type_of_buddy(){
		$data ['cod_tipo_buddy'] = $_POST["code"];
		$data ['condicion'] = 'inactivo';
		$this->buddyType_model->update($data);	
		$this->type_of_buddy('El tipo de buddy ha sido inactivado exitosamente');
	}
	//------------------------------------------END OF TYPE OF BUDDY-------------------------------------
	
	//------------------------------------------TYPE OF INSTITUTIONS--------------------------------------------
	function type_of_institution($msg){
		$data['types'] = $this->institution_model->get_types();
		$data['msg'] = $msg;
		$this->load->view('management/tables/type_of_institution/index', $data);
	}
	
	function new_type_of_institution(){
		$this->form_validation->set_rules('institutionTypeCode', 'InstitutionTypeCode', 'required|numeric|callback_institutionTypeCode_check');
		$this->form_validation->set_rules('description', 'Description', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('management/tables/type_of_institution/new_type');
		}
		else
		{
			$data ['tipo_cod_inst_edu'] = $_POST["institutionTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = 'activo';
	
			$this->institution_model->insert_type($data);	
			$this->type_of_institution('Nuevo tipo de institucion guardado exitosamente');		
		}
	}
	
	function institutionTypeCode_check($str)
	{
		$types = $this->institution_model->get_types();
		$exist = false;
		foreach($types as $t){
			if($t['tipo_cod_inst_edu'] == $str)
				$exist = true;
		}
		
		if ($exist)
		{
			$this->form_validation->set_message('institutionTypeCode_check', 'El c&oacute;digo ya existe, introduzca uno nuevo.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_type_of_institution($code){
		$this->form_validation->set_rules('institutionTypeCode', 'InstitutionTypeCode', 'required');
		$this->form_validation->set_rules('description', 'Description', 'required');
		$this->form_validation->set_rules('condition', 'Condition', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['type'] = $this->institution_model->find_type($code);
			$data['type'] = $data['type'][0];
			$this->load->view('management/tables/type_of_institution/edit_type', $data);
		}
		else
		{
			$data ['tipo_cod_inst_edu'] = $_POST["institutionTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = $_POST["condition"];
	
			$this->institution_model->update_type($data);	
			$this->type_of_institution('El tipo de institucion ha sido actualizado exitosamente');		
		}
	}
	
	function inactivate_type_of_institution(){
		$data ['tipo_cod_inst_edu'] = $_POST["code"];
		$data ['condicion'] = 'inactivo';
		$this->institution_model->update_type($data);	
		$this->type_of_institution('El tipo de institucion ha sido inactivado exitosamente');
	}
	//------------------------------------------END OF TYPE OF INSTITUTION-------------------------------------

	//------------------------------------------TYPE OF DISABILITY--------------------------------------------
	function type_of_disability($msg){
		$data['types'] = $this->disability_model->all();
		$data['msg'] = $msg;
		$this->load->view('management/tables/type_of_disability/index', $data);
	}
	
	function new_type_of_disability(){
		$this->form_validation->set_rules('disabilityTypeCode', 'DisabilityTypeCode', 'required|numeric|callback_disabilityTypeCode_check');
		$this->form_validation->set_rules('description', 'Description', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('management/tables/type_of_disability/new_type');
		}
		else
		{
			$data ['cod_discapacidad'] = $_POST["disabilityTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = 'activo';
	
			$this->disability_model->insert($data);	
			$this->type_of_disability('Nuevo tipo de discapacidad guardado exitosamente');		
		}
	}
	
	function disabilityTypeCode_check($str)
	{
		$types = $this->disability_model->all();
		$exist = false;
		foreach($types as $t){
			if($t['cod_discapacidad'] == $str)
				$exist = true;
		}
		
		if ($exist)
		{
			$this->form_validation->set_message('disabilityTypeCode_check', 'El c&oacute;digo ya existe, introduzca uno nuevo.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_type_of_disability($code){
		$this->form_validation->set_rules('disabilityTypeCode', 'DisabilityTypeCode', 'required');
		$this->form_validation->set_rules('description', 'Description', 'required');
		$this->form_validation->set_rules('condition', 'Condition', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['type'] = $this->disability_model->find($code);
			$data['type'] = $data['type'][0];
			$this->load->view('management/tables/type_of_disability/edit_type', $data);
		}
		else
		{
			$data ['cod_discapacidad'] = $_POST["disabilityTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = $_POST["condition"];
	
			$this->disability_model->update($data);	
			$this->type_of_disability('El tipo de discapacidad ha sido actualizado exitosamente');		
		}
	}
	
	function inactivate_type_of_disability(){
		$data ['cod_discapacidad'] = $_POST["code"];
		$data ['condicion'] = 'inactivo';
		$this->disability_model->update($data);	
		$this->type_of_disability('El tipo de discapacidad ha sido inactivado exitosamente');
	}
	//------------------------------------------END OF TYPE OF DISABILITY-------------------------------------
	
	//------------------------------------------TYPE OF LEADERSHIP--------------------------------------------
	function type_of_leadership($msg){
		$data['types'] = $this->leadership_model->all();
		$data['msg'] = $msg;
		$this->load->view('management/tables/type_of_leadership/index', $data);
	}
	
	function new_type_of_leadership(){
		$this->form_validation->set_rules('leadershipTypeCode', 'LeadershipTypeCode', 'required|numeric|callback_leadershipTypeCode_check');
		$this->form_validation->set_rules('description', 'Description', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('management/tables/type_of_leadership/new_type');
		}
		else
		{
			$data ['cod_pos_liderazgo'] = $_POST["leadershipTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = 'activo';
	
			$this->leadership_model->insert($data);	
			$this->type_of_leadership('Nuevo tipo de discapacidad guardado exitosamente');		
		}
	}
	
	function leadershipTypeCode_check($str)
	{
		$types = $this->leadership_model->all();
		$exist = false;
		foreach($types as $t){
			if($t['cod_pos_liderazgo'] == $str)
				$exist = true;
		}
		
		if ($exist)
		{
			$this->form_validation->set_message('leadershipTypeCode_check', 'El c&oacute;digo ya existe, introduzca uno nuevo.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_type_of_leadership($code){
		$this->form_validation->set_rules('leadershipTypeCode', 'LeadershipTypeCode', 'required');
		$this->form_validation->set_rules('description', 'Description', 'required');
		$this->form_validation->set_rules('condition', 'Condition', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['type'] = $this->leadership_model->find($code, 'cod_pos_liderazgo');
			$data['type'] = $data['type'][0];
			$this->load->view('management/tables/type_of_leadership/edit_type', $data);
		}
		else
		{
			$data ['cod_pos_liderazgo'] = $_POST["leadershipTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = $_POST["condition"];
	
			$this->leadership_model->update($data);	
			$this->type_of_leadership('El tipo de discapacidad ha sido actualizado exitosamente');		
		}
	}
	
	function inactivate_type_of_leadership(){
		$data ['cod_pos_liderazgo'] = $_POST["code"];
		$data ['condicion'] = 'inactivo';
		$this->leadership_model->update($data);	
		$this->type_of_leadership('El tipo de discapacidad ha sido inactivado exitosamente');
	}
	//------------------------------------------END OF TYPE OF LEADERSHIP-------------------------------------
	
	//-------------------------------------------TYPE OF ACTIVITY------------------------------------------------
	function type_of_activity($msg){
		$data['types'] = $this->activity_model->get_types();
		$data['msg'] = $msg;
		$this->load->view('management/tables/type_of_activity/index', $data);
	}
	
	function new_type_of_activity(){
		$this->form_validation->set_rules('activityTypeCode', 'ActivityTypeCode', 'required|numeric|callback_activityTypeCode_check');
		$this->form_validation->set_rules('description', 'Description', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('management/tables/type_of_activity/new_type');
		}
		else
		{
			$data ['cod_actividad'] = $_POST["activityTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = 'activo';
	
			$this->activity_model->insert_type($data);	
			$this->type_of_activity('Nuevo tipo de actividad guardado exitosamente');		
		}
	}
	
	function activityTypeCode_check($str)
	{
		$types = $this->activity_model->get_types();
		$exist = false;
		foreach($types as $t){
			if($t['cod_actividad'] == $str)
				$exist = true;
		}
		
		if ($exist)
		{
			$this->form_validation->set_message('activityTypeCode_check', 'El c&oacute;digo ya existe, introduzca uno nuevo.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_type_of_activity($code){
		$this->form_validation->set_rules('activityTypeCode', 'ActivityTypeCode', 'required');
		$this->form_validation->set_rules('description', 'Description', 'required');
		$this->form_validation->set_rules('condition', 'Condition', 'required');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['type'] = $this->activity_model->find_type($code);
			$data['type'] = $data['type'][0];
			$this->load->view('management/tables/type_of_activity/edit_type', $data);
		}
		else
		{
			$data ['cod_actividad'] = $_POST["activityTypeCode"];
			$data ['descripcion'] = $_POST["description"];
			$data ['condicion'] = $_POST["condition"];
	
			$this->activity_model->update_type($data);	
			$this->type_of_activity('El tipo de actividad ha sido actualizado exitosamente');		
		}
	}
	
	function inactivate_type_of_activity(){
		$data ['cod_actividad'] = $_POST["code"];
		$data ['condicion'] = 'inactivo';
		$this->activity_model->update_type($data);	
		$this->type_of_activity('El tipo de actividad ha sido inactivado exitosamente');
	}
	//------------------------------------------END OF TYPE OF BUDDY-------------------------------------
	
	function periods($msg){
		$data['periods'] = $this->club_model->get_periods();
		$data['msg'] = $msg;
		$this->load->view('management/period/index', $data);
	}
	
	function new_period(){
		$this->form_validation->set_rules('periodCode', 'PeriodCode', 'required|numeric|callback_periodCode_check');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('management/period/new_period');
		}
		else
		{
			$data ['cod_inst_edu_periodo'] = $_POST["periodCode"];
	
			$this->club_model->insert_period($data);	
			$this->periods('Nuevo periodo guardado exitosamente');		
		}
	}
	
	function periodCode_check($str)
	{
		$periods = $this->club_model->get_periods();
		$exist = false;
		foreach($periods as $p){
			if($p['cod_inst_edu_periodo'] == $str)
				$exist = true;
		}
		
		if ($exist)
		{
			$this->form_validation->set_message('periodCode_check', 'El c&oacute;digo ya existe, introduzca uno nuevo.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_period($id){
		$this->form_validation->set_rules('periodCode', 'PeriodCode', 'required|numeric');
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['period'] = $this->club_model->find_period('id_periodo', $id);
			$data['period'] = $data['period'][0];
			$this->load->view('management/period/edit_period', $data);
		}
		else
		{
			$data ['cod_inst_edu_periodo'] = $_POST["periodCode"];
	
			$this->club_model->update_period($id, $data);	
			$this->periods('El periodo ha sido actualizado exitosamente');		
		}
	}
	
	function check_period_code(){
		$periodCode = $_POST["periodCode"];
		$id_period = $_POST["id_period"];
		$period = $this->club_model->find_period('cod_inst_edu_periodo', $periodCode);
		if((count($period) > 0) && ($period[0]['id_periodo'] != $id_period)){
			echo 'error';
		}
		else {
			echo 'success';
		}
	}
	
	function link_period($id_period){
		$linked_clubs = $this->club_model->get_linked_clubs_to_period('ID_PERIODO', $id_period);
		$clubs = $this->club_model->all();
		
		$related = false;
		$cont = count($clubs);
		for($i=0; $i<$cont; $i++){
			$related = false;
			for($j=0; $j<count($linked_clubs); $j++){
				if($clubs[$i]['id_club'] == $linked_clubs[$j]['ID_CLUB'])
					$related = true;
			}
			if($related){
				unset($clubs[$i]);
			}
		}
		$clubs = array_values($clubs);
		$data['period'] = $this->club_model->find_period('id_periodo', $id_period);
		$data['period'] = $data['period'][0];
		$data['clubs'] = $clubs;
		$this->load->view('management/period/link_period', $data);
	}
	
	function save_linked_period($id_period){
		if($_POST["club"] != '0'){
			$this->club_model->link_period($id_period, $_POST["club"]);
			$this->periods('Periodo asociado exitosamente a club');
		}
		$this->periods('_');
	}
	
	//------------------------USER MANAGEMENT-----------------------------------------
	function user_management(){
		$this->load->library('pagination');
		$config['base_url'] = base_url().'management/user_management/';
		$config['total_rows'] = $this->user_model->get_count();
		$config['per_page'] = '5';
	
		$this->pagination->initialize($config);
		
		$data['users'] = $this->user_model->get_paginated($config['per_page'], $this->uri->segment(3));
		$this->load->vars($data);
		$this->load->view('management/user/index', $data);
	}
	
	public function user_detail($id){
		$data['user'] = $this->user_model->find("id_integrante", $id);
		$data['user'] = $data['user'][0];
		if($data['user']['ID_BEST_BUDDY']){
			$data['user']['BEST_BUDDY'] = $this->user_model->find("id_integrante", $data['user']['ID_BEST_BUDDY']);
			$data['user']['BEST_BUDDY'] = $data['user']['BEST_BUDDY'][0]['nombre'].' '.$data['user']['BEST_BUDDY'][0]['apellido'].'. CI: '.$data['user']['BEST_BUDDY'][0]['ci_integrante'];
		}
		if($data['user']['COD_DISCAPACIDAD']){
			$data['user']['DISCAPACIDAD'] = $this->disability_model->find($data['user']['COD_DISCAPACIDAD']);
			$data['user']['DISCAPACIDAD'] = $data['user']['DISCAPACIDAD'][0]['descripcion'];
		}
		$this->load->view('management/user/user_detail', $data);
	}
	
	function update_status_user(){
		$user = $this->user_model->find('id_integrante', $_POST["id_user"]);
		$data = array('condicion' => 'inactivo');
		if($user[0]['condicion'] == 'inactivo')
			$data = array('condicion' => 'activo');
		
		$this->user_model->update($user[0]['id_integrante'], $data);

		//The call to the user_management function it must be done through the redirect(). 
		//Because that function works with pagination, and if the call is made like this 
		//$this->user_management() the pagination doesn't initialize properly.
		$this->load->helper('url');
		redirect('/management/user_management');
	}
	
	function search_user(){
		$type = $_POST["type"];
		$text = $_POST["text"];
		switch($type){
			case 'name': 
				$users = $this->user_model->search('nombre', $text);
				$users_2 = $this->user_model->search('apellido', $text);
				$exist = false;
				for($i=0; $i < count($users_2); $i++){
					$exist = false;
					for($j=0; $j < count($users); $j++){
						if($users_2[$i]['id_integrante'] == $users[$j]['id_integrante']){
							$exist = true;
						}
					}
					if(!$exist){
						$users[count($users)] = $users_2[$j];
					}
				}
				$type = 'Nombre';
				break;
			case 'ci': 
				$users = $this->user_model->search('ci_integrante', $text);
				$type = 'C&eacute;cula';
				break;
			case 'status': 
				$users = $this->user_model->find('condicion', $text);
				$type = 'Condici&oacute;n';
				break;
		}
		$data['users'] = $users;
		$data['text'] = $text;
		$data['type'] = $type;
		$this->load->view('management/user/results', $data);
	}
	
	function buddyType_check($str)
	{
		if ($str == '-')
		{
			$this->form_validation->set_message('buddyType_check', 'Debe seleccionar un valor v&aacute;lido');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function club_check($str)
	{
		if ($str == '-')
		{
			$this->form_validation->set_message('club_check', 'Debe seleccionar un valor v&aacute;lido');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function edit_user($id){
		$this->form_validation->set_rules('name', 'Name', 'required');
		$this->form_validation->set_rules('lastname', 'Lastname', 'required');
		$this->form_validation->set_rules('ci', 'Ci', 'required');
		$this->form_validation->set_rules('genre', 'Genre', 'required');
		$this->form_validation->set_rules('birthdate', 'Birthdate', 'required');
		$this->form_validation->set_rules('buddy_type', 'Buddy_type', 'callback_buddyType_check');
		$this->form_validation->set_rules('id_club', 'Id_club', 'callback_club_check');
		$this->form_validation->set_rules('celphone', 'Celphone', 'required');
		$this->form_validation->set_rules('charge', 'Charge', 'required');
		$this->form_validation->set_rules('parish', 'Parish', 'required');
		$this->form_validation->set_rules('address', 'Address', 'required');
		$this->form_validation->set_rules('country', 'Country', 'required');
		$this->form_validation->set_rules('state', 'State', 'required');
		$this->form_validation->set_rules('municipality', 'Municipality', 'required');
		$this->form_validation->set_rules('avenue', 'Avenue', 'required');
		$this->form_validation->set_rules('street', 'Street', 'required');
		$this->form_validation->set_rules('parish', 'Parish', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');		
		/*$this->form_validation->set_rules('password', 'Password', 'required|matches[passwordConf]|md5');
		$this->form_validation->set_rules('passwordConf', 'PasswordConf', 'required');*/
		
		$this->form_validation->set_error_delimiters('<div class="error" style="color:#F00; background-color:#FF0;">', '</div>');
		
		if ($this->form_validation->run() == FALSE)
		{
			$data['disabilities'] = $this->disability_model->get_actives();	
			$data['buddy_types'] = $this->buddyType_model->get_actives();	
			$data['buddies'] = $this->user_model->all();	
			$data['clubs'] = $this->club_model->all();	
			
			$data['user'] = $this->user_model->find("id_integrante", $id);
			$data['user'] = $data['user'][0];
			$data['user']['BEST_BUDDY'] = '';
			if($data['user']['ID_BEST_BUDDY']){
				$data['user']['BEST_BUDDY'] = $this->user_model->find("id_integrante", $data['user']['ID_BEST_BUDDY']);
				$data['user']['BEST_BUDDY'] = $data['user']['BEST_BUDDY'][0]['nombre'].' '.$data['user']['BEST_BUDDY'][0]['apellido'].', CI: '.$data['user']['BEST_BUDDY'][0]['ci_integrante'];
			}
			if($data['user']['COD_DISCAPACIDAD']){
				$data['user']['DISCAPACIDAD'] = $this->disability_model->find($data['user']['COD_DISCAPACIDAD']);
				$data['user']['DISCAPACIDAD'] = $data['user']['DISCAPACIDAD'][0]['descripcion'];
			}
			$data['leadership_levels'] = $this->leadership_model->get_actives();
			$this->load->view('management/user/edit', $data);
		}
		else
		{
			$data ['ci_integrante'] = $_POST["ci"];
			$data ['nombre'] = $_POST["name"];
			$data ['apellido'] = $_POST["lastname"];
			$data ['genero'] = $_POST["genre"];
			$data ['fecha_nacimiento'] = change2ymd($_POST["birthdate"]);
			$data ['direccion'] = $_POST["address"];
			$data ['calle'] = $_POST["street"];
			$data ['avenida'] = $_POST["avenue"];
			$data ['parroquia'] = $_POST["parish"];
			$data ['municipio'] = $_POST["municipality"];
			$data ['estado'] = $_POST["state"];
			$data ['pais'] = $_POST["country"];
			$data ['telefono_celular'] = $_POST["celphone"];
			$data ['telefono_habitacion'] = $_POST["phone"];
			$data ['email'] = $_POST["email"];
			$data ['twitter'] = $_POST["twitter"];
			$data ['facebook'] = $_POST["facebook"];
			$data ['pag_web'] = $_POST["webpage"];
			$data ['COD_TIPO_BUDDY'] = $_POST["buddy_type"];
			$data ['COD_POS_LIDERAZGO'] = $_POST["charge"];
			
			if($_POST["disability"] != '-')
				$data ['COD_DISCAPACIDAD'] = $_POST["disability"];
			else
				$data ['COD_DISCAPACIDAD'] = NULL;
				
			$data ['condicion'] = $_POST["status"];
			$data ['ID_CLUB'] = $_POST["id_club"];
			//$data ['password'] = $_POST["password"];
			
			if($_POST["id_buddy"] != '')
				$data ['ID_BEST_BUDDY'] = $_POST["id_buddy"];
			else if($_POST["id_buddy"] == '')
				$data ['ID_BEST_BUDDY'] = NULL;
	
			$this->user_model->update($id, $data);			
			
			//The call to the user_management function it must be done through the redirect(). 
			//Because that function works with pagination, and if the call is made like this 
			//$this->user_management() the pagination doesn't initialize properly.
			$this->load->helper('url');
			redirect('/management/user_management');
		}
	}
	//--------------------------------------------------------------------------------
}
?>








